package com.origin.oss.solution.ali.config;

import cn.hutool.core.text.CharPool;
import cn.hutool.core.text.CharSequenceUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.origin.oss.constant.OssConstant;
import com.origin.oss.solution.ali.AliOssClient;
import com.origin.oss.solution.ali.AliOssProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

/**
 * @author origin
 * @date 2024/2/21 19:22
 */
@ConditionalOnClass(OSSClient.class)
@ConditionalOnProperty(prefix = OssConstant.OSS, name = OssConstant.OssType.ALI + CharPool.DOT + OssConstant.ENABLE
        , havingValue = OssConstant.DEFAULT_ENABLE_VALUE)
@Configuration(proxyBeanMethods = true)
@EnableConfigurationProperties(AliOssProperties.class)
public class AliOssConfiguration {

    @Bean
    public AliOssClient aliOssClient(AliOssProperties aliOssProperties) {
        AliOssConfig aliOssConfig = aliOssProperties.getOssConfig();
        return new AliOssClient(initOss(aliOssConfig), aliOssConfig);
    }

    private OSS initOss(AliOssConfig aliOssConfig) {
        String securityToken = aliOssConfig.getSecurityToken();
        AliOssClientConfig clientConfig = aliOssConfig.getClientConfig();
        if (CharSequenceUtil.isNotBlank(securityToken)) {
            return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret(), securityToken);
        } else {
            return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret()
                    , Optional.ofNullable(clientConfig).orElse(new AliOssClientConfig()).toClientConfig());
        }
    }

}
